<?php
// +----------------------------------------------------------------------
// | Created by [ PhpStorm ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 上海到啦网络科技有限公司.
// +----------------------------------------------------------------------
// | Create Time ( 2017/8/22 0022 - 上午 10:31)
// +----------------------------------------------------------------------
// | Author: tangyijun <251784425@qq.com>
// +----------------------------------------------------------------------
namespace app\extra;
use think\Config;
use think\Db;

/**
 * Class General
 * @package app\extra
 * 通用的插入以及更新的方法
 */
class General
{
    //是否开启创建发布时间
    const CREATE_TIME_ON = true;
    const CREATE_TIME_OFF = false;
    //是否开启排序，如果开启则以当前时间作为排序
    const ORDER_ON = true;
    const ORDER_OFF = false;
    //是否开启更新是添加更新时间
    const UPDATE_TIME_ON = true;
    const UPDATE_TIME_OFF = false;

    /**
     * @param $table_name
     * @param $field
     * @param $field_type
     * @param $default_value
     * @param string $comment
     * @return bool
     * 检查一个字段是否存在
     */
    public static function existField($table_name, $field, $field_type, $default_value, $comment = ''){
        $table_name = Config::get('database.prefix') . $table_name;
        $sql = 'Describe `' . $table_name . '` `' . $field . '`';
        $res = Sql::_query($sql);
        //创建sql
        if (empty($res)) {
            $sql = 'alter table `' . $table_name . '` add `' . $field . '` ' . $field_type . ' not null default = ' . $default_value . ' cooment ' . $comment;
            try {
                Db::startTrans(); //开启事务
                Sql::_query($sql);
            } catch (\Exception $e) {
                //sql执行失败回滚事务
                Db::rollback();
                return ['errorMsg'=>$e->getMessage()];
            }
            Db::commit();
        }
        return true;
    }

    /**
     * @param $table_name
     * @param bool $is_create_time
     * @param bool $is_order
     * @return array|int|string
     * 通用的插入方法
     */
    public static function generalAdd($table_name, $is_create_time = self::CREATE_TIME_ON, $is_order = self::ORDER_OFF)
    {
        $post = request()->post(); //接受表单的额值
        //如果是更新，直接调用更新方法
        if(!empty($post['id'])){
            return self::generaSave($table_name);
        }
        //上传文件
        if (!empty($_FILES)) {
            $upload_info = upload();
            $post['file_path'] = $upload_info['file_path'];
        }
        //开启
        if ($is_create_time === self::CREATE_TIME_ON) {
            $res = self::existField($table_name,'create_time','int(11)',0,'创建时间');
            if(!$res){
                return ['errorMsg'=>$res['errorMsg']];
            }
            $post['create_time'] = time();
        }
        //是否开启排序,如果数据库中没有排序字段则会自动创建该字段
        if ($is_order === self::CREATE_TIME_ON) {
            $res = self::existField($table_name,'order_by','int(11)',0,'排序');
            if(!$res){
                return ['errorMsg'=>$res['errorMsg']];
            }
            $post['order_by'] = time();
        }
        $add = Sql::_save($table_name,$post); //执行插入
        if (!$add) {
            return ['errorMsg'=>'数据库操作失败'];
        }
        return $add;
    }

    /**
     * @param $table_name
     * @param bool $is_update_time
     * @return array|bool
     * 通用的更新方法
     */
    public static function generaSave($table_name,$is_update_time = self::UPDATE_TIME_OFF){
        $post =request()->post();
        if(!empty($_FILES)){
            $upload_info = upload();
            $post['file_path'] = $upload_info['file_path'];
        }else{
            unset($post['image']);
        }
        if($is_update_time === self::UPDATE_TIME_ON){
            $res = self::existField($table_name,'update_time','int(11)',0,'更新时间');
            if(!$res){
                return ['errorMsg'=>$res['errorMsg']];
            }
            $post['update_time'] = time();
        }
        $res = Sql::_updateByKey($table_name,$post); //执行更新
        if($res === false){
            return ['errorMsg'=> '数据库操作失败'];
        }
        return true;
    }

    /**
     * @param $param
     * @param string $where
     * @return mixed
     * 生成通用的检索条件
     */
    public static function search($param,$where = 'id > 0'){
        $get = request()->get();
        //根据获取到的get参数拼接查询条件
        $assign = [];
        foreach ($get as $k => $v){
            foreach ($param as $key => $pa){
                if($k == 'title' && $pa == 'like'){
                    $where .= " and {$key} like '%{$get['title']}%'";
                    $assign['title'] = $get['title'];
                }
                if($k == 'start_time' && $pa == 'time'){
                    $start_time = strtotime($get['start_time']);
                    $where .= " and {$key} >= {$start_time}";
                    $assign['start_time'] = $get['start_time'];
                }
                if($k == 'end_time'&&  $pa == 'time'){
                    $end_time = strtotime($get['end_time']);
                    $where .= " and {$key} <= {$end_time}";
                    $assign['end_time'] = $get['end_time'];
                }
            }
        }
        $res['where'] = $where;
        $res['search'] = $assign;
        return $res;
    }

    public static function getList(){

    }
}
